// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadElderlyList();
});

// 加载老年人列表
async function loadElderlyList() {
    try {
        const response = await fetch('/api/elderly');
        const data = await response.json();
        const table = document.getElementById('elderly-table');
        
        let html = `
            <table>
                <thead>
                    <tr>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>出生日期</th>
                        <th>联系电话</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        data.forEach(elderly => {
            html += `
                <tr>
                    <td>${elderly.name}</td>
                    <td>${elderly.gender}</td>
                    <td>${elderly.birth_date}</td>
                    <td>${elderly.phone}</td>
                    <td>
                        <button onclick="showEditElderlyForm(${elderly.id})" class="edit-btn">
                            <i class="ri-edit-line"></i>修改档案
                        </button>
                        <button onclick="deleteElderly(${elderly.id}, '${elderly.name}')" class="delete-btn">
                            <i class="ri-delete-bin-line"></i>删除档案
                        </button>
                    </td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        table.innerHTML = html;
    } catch (error) {
        console.error('Error:', error);
    }
}

// 显示添加老年人表单
function showAddElderlyForm() {
    // 添加遮罩层
    document.body.insertAdjacentHTML('beforeend', '<div class="modal-overlay"></div>');
    
    const form = `
        <div class="modal">
            <h3>添加档案</h3>
            <form id="elderly-form">
                <div>
                    <label>姓名：</label>
                    <input type="text" name="name" required>
                </div>
                <div>
                    <label>性别：</label>
                    <select name="gender">
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div>
                    <label>出生日期：</label>
                    <input type="date" name="birth_date" required>
                </div>
                <div>
                    <label>联系电话：</label>
                    <input type="tel" name="phone" required>
                </div>
                <div>
                    <label>地址：</label>
                    <input type="text" name="address">
                </div>
                <div>
                    <label>紧急联系人：</label>
                    <input type="text" name="emergency_contact">
                </div>
                <div>
                    <label>紧急联系电话：</label>
                    <input type="tel" name="emergency_phone">
                </div>
                <div class="form-buttons">
                    <button type="submit">提交</button>
                    <button type="button" onclick="closeModal()">取消</button>
                </div>
            </form>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', form);
    
    document.getElementById('elderly-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData.entries());
        
        try {
            const response = await fetch('/api/elderly', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            
            if (response.ok) {
                alert('档案添加成功！');
                closeModal();
                loadElderlyList();
            } else {
                alert('添加失败，请重试！');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('提交出错，请重试！');
        }
    });
}

// 显示修改老年人档案表单
async function showEditElderlyForm(elderlyId) {
    try {
        // 获取老年人详细信息
        const response = await fetch(`/api/elderly/${elderlyId}`);
        const elderly = await response.json();
        
        // 添加遮罩层
        document.body.insertAdjacentHTML('beforeend', '<div class="modal-overlay"></div>');
        
        const form = `
            <div class="modal">
                <h3>修改档案</h3>
                <form id="elderly-edit-form">
                    <input type="hidden" name="id" value="${elderly.id}">
                    <div>
                        <label>姓名：</label>
                        <input type="text" name="name" value="${elderly.name}" required>
                    </div>
                    <div>
                        <label>性别：</label>
                        <select name="gender">
                            <option value="男" ${elderly.gender === '男' ? 'selected' : ''}>男</option>
                            <option value="女" ${elderly.gender === '女' ? 'selected' : ''}>女</option>
                        </select>
                    </div>
                    <div>
                        <label>出生日期：</label>
                        <input type="date" name="birth_date" value="${elderly.birth_date}" required>
                    </div>
                    <div>
                        <label>联系电话：</label>
                        <input type="tel" name="phone" value="${elderly.phone}" required>
                    </div>
                    <div>
                        <label>地址：</label>
                        <input type="text" name="address" value="${elderly.address || ''}">
                    </div>
                    <div>
                        <label>紧急联系人：</label>
                        <input type="text" name="emergency_contact" value="${elderly.emergency_contact || ''}">
                    </div>
                    <div>
                        <label>紧急联系电话：</label>
                        <input type="tel" name="emergency_phone" value="${elderly.emergency_phone || ''}">
                    </div>
                    <div class="form-buttons">
                        <button type="submit">保存</button>
                        <button type="button" onclick="closeModal()">取消</button>
                    </div>
                </form>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', form);
        
        document.getElementById('elderly-edit-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            
            try {
                const response = await fetch(`/api/elderly/${data.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('档案修改成功！');
                    closeModal();
                    loadElderlyList();
                } else {
                    alert('修改失败：' + result.message);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('修改出错，请重试！');
            }
        });
    } catch (error) {
        console.error('Error:', error);
        alert('加载档案信息失败，请重试！');
    }
}

// 删除老年人档案
async function deleteElderly(elderlyId, elderlyName) {
    if (!confirm(`确定要删除 ${elderlyName} 的档案吗？\n注意：这将同时删除该用户的所有健康记录和健康建议！`)) {
        return;
    }
    
    try {
        const response = await fetch(`/api/elderly/${elderlyId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('档案删除成功！');
            loadElderlyList();
        } else {
            alert('删除失败：' + data.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('删除出错，请重试！');
    }
}

// 关闭模态框
function closeModal() {
    document.querySelector('.modal').remove();
    document.querySelector('.modal-overlay').remove();
} 